import Vue from "vue"
import Vuex from "vuex"
import room from "./room"
import {SignalSocket} from "../SignalSocket.js";
import { POINT_CONVERSION_COMPRESSED } from "constants";
Vue.use(Vuex)

export default new Vuex.Store({  
    state:{
        table:[
            
        ],
        PublicTable:[

        ],
        sy:0,
        userMsg:{//用户信息
            GT:0,
            GTableId:0,
            Content:{
                Balance:0,
                MemberXH:''
            }
        },
        loading:0,//加载进度
        getLog:"",//加载中提示
        tips:"",//提示
        index:1,
        query:'',//查询
        userSocket:{}//socket对象
    }, 
    getters:{
        // 房间列表
        table(state){
            return state.table;
        },
        // 公共房间列表
        PublicTable(state){
            return state.PublicTable;
        },
        // 声音
        sy(state){
            return state.sy;
        },
        // 会员信息
        userMsg(state){
            return state.userMsg;
        },
        // 加载条
        loading(state){
            return state.loading;
        },
        // 提示
        Tips(state){
            return state.tips;
        },
        // 查询框
        query(state){
            return state.query;
        },
        // 请求加载中提示
        getLog(state){
            return state.getLog;
        },
        // 厅位置
        index(state){
            return state.index;
        }
    },
    mutations:{
        // 减少秒数
        posTime(state){
            for(let i=0;i<state.table.length;i++){
                if(state.table[i].RestHops>0){
                    state.table[i].RestHops--;
                }                
            }
            for(let x in state.PublicTable){
                for(let xx=0;xx<state.PublicTable[x].length;xx++){
                    state.PublicTable[x][xx].RestHops--;
                }
            }
        },
        // 修改声音
        setSy(state,x){
            state.sy=x;
        },
        // 重置加载条
        initLoagin(state){
            state.loading=0;
        },
        // 增加加载条
        setLogin(state,x){
            if(state.loading<100){
                state.loading+=x;
            }
        },
        // 设置会员信息
        setUserMsg(state,x){
           for(let i in x){
               console.log(x[i])
               if(i!='ActType'){
                   state.userMsg[i]=x[i]
               }
           }
        },
        setBalance(state,num){
            state.userMsg.Content.Balance=num;
        },
        // 初始化房间列表数据
        initTbale(state){
            state.table=[];
        },
        // 进入大厅处理
        goGameHall(state,msg){
            state.userMsg.Content.Balance!=msg.Content.Balance?state.userMsg.Content.Balance=msg.Content.Balance:false;
            state.userMsg.Content.Notice!=msg.Content.Notice?state.userMsg.Content.Notice=msg.Content.Notice:false;
            state.userMsg.GT!=msg.GT?state.userMsg.GT=msg.GT:false;
            state.table=msg.Content.RoomArray;
        },
        // 初始化房间彩池数据
        initTableRoom(state,index){
            state.table[index].ChipsSum="0/0,0/0,0/0,0/0,0/0";
        },
        // 广播房间列表数据
        changeTableRoom(state,msg){
            for(let i=0;i<state.table.length;i++){
                if(state.table[i].GType==msg.GType&&state.table[i].TId==msg.TId){
                    for(let a in msg){
                        if(msg[a]!='')
                        state.table[i][a]!=msg[a]?state.table[i][a]=msg[a]:false;
                    }
                }
            }
        },
        //记录房间号
        setRoomNumber(state,num){
            state.userMsg.GT=num.GT;
            state.userMsg.GTableId=num.GTableId;
            state.userMsg.Content.Balance!=num.Content.Balance?state.userMsg.Content.Balance=num.Content.Balance:false;
        },
        //请求加载中
        changeLoading(state,x){
            window.TimeOut?clearTimeout(window.TimeOut):false;
            window.AJAXtime?clearTimeout(window.AJAXtime):false;
            window.interrupt?clearTimeout(window.interrupt):false;
            if(x=='下注中'){
                this.commit("room/setBetStatus",true);
                window.AJAXtime= setTimeout(()=>{//获取结果超时请求查看
                    $.ajax({
                        url:window.api.getThisMon,
                        data:{
                            "UserId":state.userMsg.UId,
                            "RandCode":state.userMsg.RandCode,
                            "GameType":state.userMsg.GT,
                            "GTableId":state.userMsg.GTableId
                        },
                        success:(data)=>{
                            if(data.State==1000){
                                console.log(data.Msg+"下注超时第一次请求")
                                if(data.Msg.BetInfo){//存在下注
                                    let Msg=data.Msg;
                                    let a={Content:{Balance:Msg.Balance, BetInfo:Msg.BetInfo , CurrJu:Msg.Curr_Xue, CurrXue:Msg.Curr_Ju, BetHistory:Msg.BetHistory }};//模拟socket返回数据
                                    this.commit("room/getBetInfo",a);
                                    this.commit("changeLoading",false);
                                    this.commit("room/setBetStatus",false);
                                }						
                            }
                        }
                    })
                },5000)	
            }else{
                state.getLog=x;
            }
            
        },
        // 设置查询框数值
        query_open(state,x){
            state.query=x;
        },
        // 设置公共列表信息
        setPublicTable(state,msg){
            state.PublicTable=msg.Content;
        },
        // 设置提示信息
        setTips(state, x){
            if(x.Out){
                sessionStorage.clear();
                let UId=state.userMsg.UId
                let RandCode=state.userMsg.RandCode;
                // window.Socket.uSend(JSON.stringify({ActType:12,UId,RandCode}));
                window.Socket.allStop()
                if(x.data) {
                    alert(x.data);
                }
                state.setUserMsg={},
                window.location.href="#/"
            }else{
                state.tips=x;
            }
        },
        // 检查下注返回是否超时
		BetTimeOut(state){
            $.ajax({
                url:window.api.getThisMon,
                data:{
                    "UserId":state.userMsg.UId,
                    "RandCode":state.userMsg.RandCode,
                    "GameType":state.userMsg.GT,
                    "GTableId":state.userMsg.GTableId
                },
                success:(data)=>{
                    console.log(data.Msg)
                    if(data.State==1000){
                        let Msg=data.Msg;
                        let a={Content:{Balance:Msg.Balance, BetInfo:Msg.BetInfo , CurrJu:Msg.Curr_Xue, CurrXue:Msg.Curr_Ju, BetHistory:Msg.BetHistory }};//模拟socket返回数据
                        if(data.Msg.BetInfo){//存在下注
                            this.commit("room/getBetInfo",a);
                            this.commit("changeLoading",false);
                            this.commit("setTips","成功下注");
                        }else{//没有获取到下注
                            this.commit("room/setBetInLoser")//下注失败回调
                            this.commit("changeLoading",false);
                            this.commit("setTips","对不起，网络繁忙！下注失败！");
                        }						
                    }
                },
                error:()=>{//没有获取到下注
                    this.commit("room/setBetInLoser")//下注失败回调
                    this.commit("changeLoading",false);
                    this.commit("setTips","对不起，网络繁忙！下注失败");
                    }
            })
            //恢复下注不超时
            this.commit("room/setBetStatus",false);
        },
        // 返回数据发送错误
		errorPs(state,x){
			switch(x.ErrorCode){
				case 10001:
                    this.commit("setTips",{data:"当前账号已锁定，请与客服联系,将自动退出游戏", Out:true});
                    break;
                case 10002:
                    this.commit("setTips",{data:"当前账号本次登陆请求被拒绝，请稍候重试,将自动退出游戏",Out: true});
                    break;
                case 10003:
                    this.commit("setTips",{data:"服务器繁忙，请稍候登录,将自动退出游戏", Out:true});
                    break;
                case 10004:
                    this.commit("setTips",{data:"非法操作，请稍候登录,将自动退出游戏",Out: true});
                    break;
                case 10005:
                    this.commit("setTips","服务器繁忙，请重试");
                    break;
                case 10006:
                    this.commit("setTips","数据格式有误，请重试");
                    break;
                case 10007:
                    this.commit("setTips","数据包格式有误，请重试");
                    break;
                case 10008:
                    this.commit("setTips",{data:"用户名有误，请重新登录,将自动退出游戏", Out:true});
                    break;
                case 10019:
					this.commit("setTips","超出限红范围，本次押注无效");
					this.commit("room/setBetInLoser",x);
                    break;
                case 10020:
					this.commit("setTips","押注超时，请下局再押");
					this.commit("room/setBetInLoser",x);
                    break;
                case 10021:
					this.commit("setTips","账户余额不足");
                    break;
                case 10022:
                    this.commit("setTips",{data:"登录超时，请重新登录,将自动退出游戏", Out:true});
                    break;
                case 10023:
                    this.commit("setTips",{data:"数据行为传入有误，请重新登录,将自动退出游戏",Out: true});
                    break;
                case 10024:
                    this.commit("setTips",{data:"登录已超时，请重新登录,将自动退出游戏",Out: true});
                    break;
                case 10025:
                    this.commit("setTips","投注异常");
                    break;
                case 10026:
                    this.commit("setTips",{data:"当前账号禁止投注，请与客服联系,将自动退出游戏", Out:true});
                    break;
                case 10027:
                    this.commit("setTips","投注失败，请重试");
                    break;
			}
			this.commit("changeLoading",false);
        },
        // 设置所在大厅
        steHallIndex(state,num){
            state.index=num;
        }
    },
    actions:{
        // 首次登陆启动方法
        starGame(context){
            console.log('启动')
            window.Socket=null;
            // 保存用户重要数据
            let  socketUrl=sessionStorage.getItem("socketUrl").split('|');
            let jsIndex=0;
            let a={
                UId:sessionStorage.getItem("uid"),
                RandCode:sessionStorage.getItem("RandCode"),
                uidType:sessionStorage.getItem("uidType"),
            }
            this.commit("setUserMsg",a);
            // 引入signair代理
            // 动态加载HUBS代理文件
            let __this=this;
            let setLoad=function(){
				//加载成功，促进加载条
				this.commit("setLogin",50);
				// 初始化配置
					// 心跳包
					let head='{"ActType":11,"ConnectionId":"","GT":"","UId":"' + a.UId + '","ErrorCode":10000,"RandCode":"'+ a.RandCode + '"}'
					// 绑定数据处理函数
					function mesg(id,msg){
						// console.log("确认收到数据：");
						// console.log(JSON.parse(msg));
                        // console.log(id);
						if(id!=this.state.userMsg.UId&&!this.state.userMsg.RandCode){
							this.commit("setTips",{data:"非正常登陆",Out:true})
							return false;
						}

						msg=JSON.parse(msg)//数据转换成JSON
						if(msg.ErrorCode!=10000&&msg.ErrorCode){
							this.commit("errorPs",msg);//进行数据错误判断
							return false;
						}
						switch(msg.ActType){//执行数据交互任务
                            case 1://登陆
								this.commit("setLogin",50);//登陆成功
								this.commit("setUserMsg",msg);
								this.commit("changeLoading",'');
							break;
							case 2://投注
								this.commit("room/getBetInfo",msg);
								this.commit("changeLoading",'');
							break;
                            case 3://大厅
								this.commit("goGameHall",msg);
								this.commit("changeLoading",'');
							break;
                            case 5://房间
                                this.commit("setRoomNumber",msg);
								this.commit("room/setRoomInit",msg.Content);
                                this.commit("changeLoading",'');
                                if(msg.GT==1){
                                    window.AudioObj.Play(['welcomeBJL'])
                                }
                                else if(msg.GT==2){
                                    window.AudioObj.Play(['welcomelh'])
                                }
							break;
                            case 9://开奖
                                this.commit("setRoomNumber",msg);
								this.commit("room/openRule",msg.Content);
							break;
								// 下注比例信息更新
                            case 19:
                                this.commit("changeTableRoom",msg)
								this.commit("room/setUserAll",msg);
							break;
                            case 17://开局返回
								this.commit("room/openNewGame",msg.Content);
							break;
							// 停止下注
							case 23:
								this.commit("room/setStop",msg);
							break;
							case 22://断开链接
								this.commit("setTips",{data:"当前账号已在其他地方登陆,即将自动退出游戏",Out: true})
							break;
							// 本局作废
							case 24:
								this.commit("room/clearGmae",msg);
							break;
							case 28:
								this.commit("setPublicTable",msg);
							break;
                            // case 30://多台
                            //     clearTimeout(window.TimeOut);
							// 	clearTimeout(window.interrupt);
							// 	this.commit("setManyGame",msg)
							// 	this.commit("changeLoading",'');
							// break;
							default:
								this.commit("changeTableRoom",msg)
						}
						
					}
					// 发送信息回调函数
					function sendFun(Msg){
						let a= JSON.parse(Msg);
						if(a.ActType==2){//发送的是下注信息
							// console.log("下注了")
							window.TimeOut=setTimeout(()=>{
								this.commit("changeLoading","下注中");
							},500)
						}else if(a.ActType==11||a.ActType==28||a.ActType==12){
                            // 心跳包不执行任何动作
                        }
						else{
							window.TimeOut=setTimeout(()=>{
								this.commit("changeLoading",'loding');
								window.interrupt=setTimeout(()=>{
									console.log("数据超时");
									context.commit("errorPs",{ErrorCode:10022});
								},20000)
							},500)
						}

					}
					// 发送错误回调
					function errro(msg){
						console.log("发生错误事件"+msg)
					}
					// 确认网络中断触发
					function onclose(){
                        if(sessionStorage.getItem('RandCode')){
                            console.log("无法链接到服务器");
                                setTimeout(()=>{
                                    this.commit("setTips",{data:"与服务器链接断开，请重新登陆", Out:true})	
                                },1000)                            
                        }
	
					}
					// 网络出现延迟高触发
					function Slow(){
						console.log("当前网络较慢")
					}
					// 网络出现重新链接触发
					function res(){
						console.log("网络正在重新链接")
					}
					// 网络重新链接成功
					function resYes(){
						console.log("网络重新链接成功")
					}
					// 首次链接成功回调
					function Success(){
						// 发送登陆验证数据
						this.commit("changeLoading",'登陆中');
                        window.Socket.uSend('{"ActType":1,"ClientIp":"","ConnectionId":"","Content":{"UId":"' + this.state.userMsg.UId + '"},"ErrorCode":10000,"RandCode":"' + this.state.userMsg.RandCode + '","UId":"' + this.state.userMsg.UId + '"}');
                        this.dispatch("starSetRoomTable")
                    }
                    // 开启链接
                    window.Socket= new SignalSocket("http://"+socketUrl[jsIndex]+"/signalr",this.state.userMsg.UId,head,25000,mesg.bind(context),errro,sendFun.bind(context),onclose.bind(context),Slow,res,resYes,Success.bind(context));
			}
            function loadJs(x){
                let HubJS= document.createElement("script");
                HubJS.src="http://"+socketUrl[x]+"/signalr/hubs";                  
                // 插入到文档
                document.getElementsByTagName("head")[0].appendChild(HubJS);
                HubJS.onload=setLoad.bind(__this)
                HubJS.onerror=function(){//加载动态JS文件失败，服务器关闭
                    jsIndex++;
                    if(jsIndex==socketUrl.length){
                        context.commit("setTips",{data:"加载系统文件失败，请稍后重试", Out:true});
                    }
                    else{
                        loadJs(jsIndex);
                    }
                }
            }
            loadJs(jsIndex);
            return true;
        },
        // 减少房间列表时间的启动定时器方法
        starSetRoomTable(context){
            setInterval(()=>{
                context.commit("posTime")
            },1000)
        },
        initLoagin(context){
            context.commit('initLoagin');
            return true;
        }
    },
    modules:{
        room,
    }
})
